import { loginApi, getInfoApi, getDetailUserInfoApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, data) {
      // 存入token
      state.token = data
      // 本地持久化
      setToken(data)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, data) {
      state.userInfo = data
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 获取token
    async loginAction(context, data) {
      const res = await loginApi(data)
      // console.log(data)
      context.commit('setToken', res)
    },
    // 获取用户资料
    async getUserInfoAction(context) {
      const res = await getInfoApi()
      const res2 = await getDetailUserInfoApi(res.userId)
      context.commit('setUserInfo', { ...res, ...res2 })
    },
    quitAction(context) {
      // 清除token
      context.commit('removeToken')
      // 清除用户资料
      context.commit('removeUserInfo')
    }
  }
}
